package com.wy.projectssj.dao.impl;

import com.wy.projectssj.dao.RoleDao;
import com.wy.projectssj.domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: wy
 * @Date:2019/8/29 9:00
 */
@Repository
public class RoleDaoImpl implements RoleDao {
       @Autowired
       private JdbcTemplate jt;
    /**
     * 查询所有
     * @return
     */
    @Override
    public List<Role> findAll() {
         String sql="select * from role";
        List<Role> roleList=null;
        try {
             roleList = jt.query(sql, new BeanPropertyRowMapper<>(Role.class));
        } catch (DataAccessException e) {

        }
        return roleList;
    }

    @Override
    public int save(Role role) {
        int result=-1;
         String sql="insert into role values(?,?,?)";
        try {
            result = jt.update(sql,role.getId(), role.getRoleName(), role.getRoleDesc());
        } catch (DataAccessException e) {

        }
        return result;
    }

    @Override
    public int delete(String[] ids) {
        int result=-1;
        String s="delete from role where 1=1 and id in (";
        StringBuilder sql=new StringBuilder(s);
        for (int i = 0; i <ids.length ; i++) {
            if(i==ids.length-1){
                sql.append("?)");
            }else{
                sql.append("?,");
            }
        }
        try {
            result = jt.update(sql.toString(), ids);
        } catch (DataAccessException e) {

        }
        return result;
    }

    @Override
    public List<Role> findById(String uid) {
        String sql="select * from role where id in(select roleId from users_role where userId=?)";
        List<Role>  list=null;
        try {
          list = jt.query(sql, new BeanPropertyRowMapper<>(Role.class), uid);
        } catch (DataAccessException e) {
        }
        return list;
    }


}
